#include "../../include/Tileset/tilesetObject.hpp"
#include "../../include/Tileset/tilesetPolygon.hpp"
#include "../../include/Tileset/tilesetEllipse.hpp"
#include "../../include/Tileset/tilesetPolyline.hpp"
#include "../../include/Tileset/tilesetProperties.hpp"
#include <string>
#include <tinyxml.h>

namespace Tmx {
  Object::Object() {
    width = 0;
	height = 0;
	x = 0;
	y = 0;
	rotation = 0;
	gid = 0;
	interactable = 0;
	visible = 1;
	pPolygon = NULL;
	pEllipse = NULL;
	pPolyline = NULL;
	properties = NULL;
  } 
  
  Object::~Object() {
	//std::cout << "Object destructor called\n";
    if (pPolygon != 0) {
	  delete pPolygon;
	  pPolygon = NULL;
	}
	if (pEllipse != 0) {
	  delete pEllipse;
	  pEllipse = NULL;
	}
	if (pPolyline != 0) {
	  delete pPolyline;
	  pPolyline = NULL;
	}
	if (properties != 0) {
		delete properties;
		properties = NULL;
	}
  }
  
  void Object::parse(TiXmlNode *objectNode)
  {
    const TiXmlElement *objectElement = objectNode->ToElement();
	const char *tempName = objectElement->Attribute("name");
	const char *tempType = objectElement->Attribute("type");
	if (tempType) type = tempType;
	objectElement->Attribute("x", &x);
	objectElement->Attribute("y", &y);
	objectElement->Attribute("width", &width);
	objectElement->Attribute("height", &height);
	objectElement->Attribute("gid", &gid);
	// handle object types
	TiXmlNode *polygonNode = objectNode->FirstChild("polygon");
	if (polygonNode) {
	  if (pPolygon) 
	    delete pPolygon;
      pPolygon = new Polygon();
	  pPolygon->parse(polygonNode);
	}
	const TiXmlNode *ellipseNode = objectNode->FirstChild("ellipse");
	if (ellipseNode) {
	  if (pEllipse) 
	    delete pEllipse;
	  // The regular x, y, width, height attributes are used to determine the size of the ellipse
	  pEllipse = new Ellipse(x,y,width,height); 
	}
	
	TiXmlNode *polylineNode = objectNode->FirstChild("polyline");
	if (polylineNode) {
	  if (pPolyline) 
	    delete pPolyline;
      pPolyline = new Polyline();
	  pPolyline->parse(polylineNode);
	}

	TiXmlNode *propertiesNode = objectNode->FirstChild("properties");
	if (propertiesNode != 0) {
		if (properties)
			delete properties;
		properties = new Properties();
		properties->parse(propertiesNode);
		interactable = true;
	}
  }
}; // namespace Tmx
